package com.daxt.controller.sysarchives;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;

import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.UserInfoUtil;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.annotations.OperLog;
import com.daxt.mapper.sys.*;
import com.daxt.model.dic.DicDocFileType;
import com.daxt.model.dic.DicDocPattern;
import com.daxt.model.dto.BaseQueryDto;
import com.daxt.model.dto.Classifys;
import com.daxt.model.service.archives.vo.*;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.base.vo.Dept;
import com.daxt.model.service.base.vo.Role;
import com.daxt.model.service.base.vo.UserClassify;
import com.daxt.service.ArchivesService;
import com.daxt.service.ArchivesTypeDocService;
import com.daxt.service.UserService;
import com.daxt.utils.ArchivesUtil;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.mapper.archives.ArchivesBaseMapper;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.archives.ArchivesTypeDocMapper;
import com.daxt.model.service.archives.param.SetGenArchivalNum;
import com.daxt.model.service.archives.param.SetGenClassNum;
import com.daxt.model.service.archives.param.SortCol;
import com.daxt.model.service.archives.result.ArchivesTypeList;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "门类管理")
@RestController
public class ArchivesTypeController {

    @Autowired
    private ArchivesFondsMapper archivesFondsMapper;
    @Autowired
    private ArchivesTypeMapper archivesTypeMapper;
    @Autowired
    private ArchivesDocMapper archivesDocMapper;
    @Autowired
    private ArchivesBaseMapper archivesBaseMapper;
    @Autowired
    private ArchivesTypeDocMapper archivesTypeDocMapper;
    @Autowired
    private UserClassifyMapper userClassifyMapper;
    @Autowired
    private ArchivesService archivesService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private ArchivesTypeDocService archivesTypeDocService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleMapper roleMapper;

    public String createTenantId(String tenantId) {
        int i = 0;
        for (; i < tenantId.split("").length; i++) {
            if (!tenantId.split("")[i].equals("0")) {
                break;
            }
        }
        String newId = (Integer.parseInt(tenantId.substring(i)) + 1) + "";
        int j = (8 - newId.length());
        for (int k = 0; k < j; k++) {
            newId = "0" + newId;
        }
        return newId;

    }

    @ApiOperation(value = "获取档案门类列表", notes = "")
    @GetMapping("/archivesType")
    @LoginAuth()
    public Result<List<ArchivesTypeList>> listType(@ApiIgnore @LoginUser UserInfo loginUser) {
        //获取用户数据权限
        Classifys c = userService.buildUserClassifys(loginUser);
        List<Long> categoryIds = c.getCategoryIds();//门类ids

        List<ArchivesTypeList> info = archivesFondsMapper.findPermissionTypeList(null,categoryIds);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, info);
    }

    @ApiOperation(value = "根据全宗获取档案门类列表", notes = "")
    @GetMapping("/archivesType/{fondsId}")
    @LoginAuth()
    public Result<List<ArchivesTypeList>> listTypeByfondsNum(@ApiIgnore @LoginUser UserInfo loginUser, @PathVariable("fondsId") String fondsId) {

        //获取用户数据权限
        Classifys c = userService.buildUserClassifys(loginUser);
        List<Long> categoryIds = c.getCategoryIds();//门类ids

        List<ArchivesTypeList> info = archivesFondsMapper.findPermissionTypeList(fondsId,categoryIds);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, info);
    }

    @ApiOperation(value = "获取档案门类列表,无权限", notes = "")
    @GetMapping("/archivesType/noPrower")
    public Result<List<ArchivesTypeList>> listTypeByfondsNum(@RequestParam("fondsId") String fondsId) {
        List<ArchivesTypeList> info = archivesFondsMapper.findPermissionTypeList(fondsId,null);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, info);
    }

    @ApiOperation(value = "添加档案门类", notes = "")
    @PostMapping("/archivesType")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> saveType(@RequestBody @Valid ArchivesType entity) {
        try {
            ArchivesFonds af = archivesFondsMapper.selectById(entity.getFondsId());
            entity.setFondsNum(af.getFondsNum());

            if (entity.getSort() == null)entity.setSort(1);
            int rows = archivesTypeMapper.insert(entity);
            if (rows > 0) {
                QueryWrapper<ArchivesBase> queryWrapperTypeDoc = new QueryWrapper<>();
                queryWrapperTypeDoc.eq("isMust", "1");
                List<ArchivesBase> baseList = archivesBaseMapper.selectList(queryWrapperTypeDoc);

                List<ArchivesTypeDoc> atDocList = new ArrayList<>();
                for (ArchivesBase aBase : baseList) {
                    //System.out.println("entity : " + entity.getModel());

                    //添加卷
                    if (DicDocPattern.PATTERN_1.getKey().equals(entity.getModel()) && !aBase.getExtColumn().equals("itemNum")) {
                        atDocList.add(ArchivesUtil.initializeArchivesTypeDoc(aBase, entity));
                    }

                    //添加件
                    ArchivesType entityDoc = new ArchivesType();
                    BeanUtils.copyProperties(entity, entityDoc);
                    entityDoc.setModel("0");
                    //System.out.println("entityDoc : " + entityDoc.getModel());
                    atDocList.add(ArchivesUtil.initializeArchivesTypeDoc(aBase, entityDoc));

                }
                archivesTypeDocService.saveBatch(atDocList);

                QueryWrapper<Role> roleQueryWrapper=new QueryWrapper<>();
                roleQueryWrapper.eq("fondsId",entity.getFondsId());
                List<Role> roleList= roleMapper.selectList(roleQueryWrapper);
                //为对应角色设置分类权限
                for(Role role:roleList){
                    QueryWrapper<UserClassify> ucQuery=new QueryWrapper<>();
                    ucQuery.eq("type",0);
                    ucQuery.eq("roleId",role.getId());
                    ucQuery.eq("classifyId",entity.getFondsId());
                    int count= userClassifyMapper.selectCount(ucQuery);
                    if(count<=0){
                        UserClassify userClassify=new UserClassify();
                        userClassify.setClassifyId(Long.parseLong(entity.getFondsId()));
                        userClassify.setRoleId(role.getId());
                        userClassify.setType(0);
                        //fondsId+typeId+父级Id+自己id
                        userClassify.setTreeId(entity.getFondsId());
                        userClassifyMapper.insert(userClassify);
                    }


                    UserClassify userClassify=new UserClassify();
                    userClassify.setClassifyId(entity.getId());
                    userClassify.setRoleId(role.getId());
                    userClassify.setType(1);
                    //fondsId+typeId+父级Id+自己id
                    userClassify.setTreeId(entity.getFondsId()+"-"+entity.getId());
                    userClassifyMapper.insert(userClassify);
                }
            }
            return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
                    null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
        }
    }

    @ApiOperation(value = "修改档案门类", notes = "")
    @PutMapping("/archivesType")
    public Result<String> editType(@RequestBody @Valid ArchivesType entity) {

        QueryWrapper<ArchivesType> queryWrapper = new QueryWrapper();

        queryWrapper.select("id");


        queryWrapper.eq("typeNum",entity.getTypeNum());
        queryWrapper.notIn("id",entity.getId());
//        queryWrapper.last(" and id !=" + entity.getId());
//        List<ArchivesType> list = archivesTypeMapper.selectList(queryWrapper);
        int i  = archivesTypeMapper.selectCount(queryWrapper);

        if (i > 0) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "档案类型的类名或类号不能重复！！！", null);
        }

        QueryWrapper<ArchivesDoc> queryWrapperDoc = ArchivesUtil.builBaseQueryWrapper(new BaseQueryDto(entity.getFondsId(),entity.getTypeNum()));

        Integer selectCount = archivesDocMapper.selectCount(queryWrapperDoc);
        if (selectCount > 0) {
            ArchivesType selectById = archivesTypeMapper.selectById(entity.getId());
//			if(!entity.getFileType().equals(selectById.getFileType()))
//				return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "修改文件类型，请先删除门类下的档案！！！", null);
//			if(!entity.getModel().equals(selectById.getModel()))
//				return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "修改卷/件，请先删除门类下的档案！！！", null);

            // add by dm @date:2021-05-14	修改卷/件，保留原来的生成规则
            if (!entity.getModel().equals(selectById.getModel())) {
                entity.setModelOld(selectById.getModel());
                entity.setGenArchivalNumOld(selectById.getGenArchivalNum());
                entity.setGenTypeOld(selectById.getGenType());
                entity.setGenClassNumOld(selectById.getGenClassNum());
                entity.setGenClassTypeOld(selectById.getGenClassType());

                String modelOld = selectById.getModelOld();
                String genArchivalNumOld = selectById.getGenArchivalNumOld();
                String genTypeOld = selectById.getGenTypeOld();
                String genClassNumOld = selectById.getGenClassNumOld();
                String genClassTypeOld = selectById.getGenClassTypeOld();
                if (StringUtils.isNotBlank(modelOld)) {
                    entity.setGenArchivalNum(genArchivalNumOld);
                    entity.setGenType(genTypeOld);
                    entity.setGenClassNum(genClassNumOld);
                    entity.setGenClassType(genClassTypeOld);
                }
            }
            // add end

        }
        if (entity.getSort() == null)
            entity.setSort(1);
        int rows = archivesTypeMapper.updateById(entity);
        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
                null);
    }

    @ApiOperation(value = "删除档案门类", notes = "")
    @DeleteMapping("/archivesType")
    public Result<String> delType(@RequestBody @Valid @NotEmpty List<String> ids) {
        List<ArchivesType> selectBatchIds = archivesTypeMapper.selectBatchIds(ids);
        boolean flag = false;
        for (ArchivesType archivesType : selectBatchIds) {

            QueryWrapper<ArchivesDoc> queryWrapper = ArchivesUtil.builBaseQueryWrapper(new BaseQueryDto(archivesType.getFondsId(),archivesType.getTypeNum()));

            List<ArchivesDoc> selectList = archivesDocMapper.selectList(queryWrapper);
            if (selectList != null && selectList.size() > 0) {
                flag = true;
            }
        }
        if (flag) {
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "请先删除门类下的档案", null);
        }
        int rows = archivesTypeMapper.deleteBatchIds(ids);
        QueryWrapper<ArchivesTypeDoc> wrapperTypeDoc = new QueryWrapper<ArchivesTypeDoc>();
        wrapperTypeDoc.in("typeId", ids);
        archivesTypeDocMapper.delete(wrapperTypeDoc);

        QueryWrapper<UserClassify> qWrapper = new QueryWrapper<UserClassify>();
        qWrapper.in("classifyId", ids);
        userClassifyMapper.delete(qWrapper);

        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), null,
                null);
    }

    @ApiOperation(value = "根据档案门类获取字段", notes = "")
    @GetMapping("/archivesType/config/{id}")
    public Result<List<ArchivesTypeDoc>> getConfig(@PathVariable("id") String id) {
        // ArchivesType archivesType = archivesTypeMapper.selectById(id);
        QueryWrapper<ArchivesTypeDoc> queryWrapper = new QueryWrapper<ArchivesTypeDoc>();
        queryWrapper.eq("typeId", id);
        List<ArchivesTypeDoc> list = archivesTypeDocMapper.selectList(queryWrapper);

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", list);
    }

    @ApiOperation(value = "获取编辑字段信息", notes = "")
    @GetMapping("/archivesType/getBaseCol/{baseId}")
    public Result<ArchivesBase> querypeCol(@PathVariable("baseId") String baseId) {
        ArchivesBase selectById = archivesBaseMapper.selectById(baseId);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", selectById);
    }

    @ApiOperation(value = "获取门类字段", notes = "")
    @GetMapping("/archivesType/getCol/{typeId}/{type}")
    public Result<List<ArchivesTypeDoc>> getTypeCol(@ApiParam("") @PathVariable("typeId") Long typeId,
                                                    @ApiParam("doc dossier") @PathVariable("type") String type) {
        QueryWrapper<ArchivesTypeDoc> queryWrapper = new QueryWrapper<ArchivesTypeDoc>();
        queryWrapper.eq("typeId", typeId);
        queryWrapper.eq("extType", type);
        List<ArchivesTypeDoc> list = archivesTypeDocMapper.selectList(queryWrapper);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", list);
    }

    @ApiOperation(value = "获取字段", notes = "")
    @GetMapping("/archivesType/cols/{typeId}/{type}")
    public Result<List<ArchivesBase>> getCols(@ApiParam("") @PathVariable("typeId") String typeId,
                                              @ApiParam("") @PathVariable("type") String type) {
        QueryWrapper<ArchivesTypeDoc> queryWrapperTypeDoc = new QueryWrapper<ArchivesTypeDoc>();
        queryWrapperTypeDoc.eq("typeId", typeId);
        queryWrapperTypeDoc.eq("extType", type);
        List<ArchivesTypeDoc> list = archivesTypeDocMapper.selectList(queryWrapperTypeDoc);
        List<Long> ids = new ArrayList<>();
        for (ArchivesTypeDoc archivesTypeDoc : list) {
            ids.add(archivesTypeDoc.getBaseId());
        }

        QueryWrapper<ArchivesBase> queryWrapperBaseList = new QueryWrapper<ArchivesBase>();
        if (ids.size() > 0)
            queryWrapperBaseList.notIn("id", ids);
        List<ArchivesBase> baseList = archivesBaseMapper.selectList(queryWrapperBaseList);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", baseList);
    }


    @ApiOperation(value = "添加门类字段", notes = "")
    @PostMapping("/archivesType/setCol")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> setTypeCol(@RequestBody ArchivesTypeDoc typeDoc) {
        try {
            QueryWrapper<ArchivesTypeDoc> wrapperDel = new QueryWrapper<>();
            wrapperDel.eq("typeId", typeDoc.getTypeId());
            wrapperDel.eq("baseId", typeDoc.getBaseId());
            wrapperDel.eq("extType", typeDoc.getExtType());
            archivesTypeDocMapper.delete(wrapperDel);
            typeDoc.setSort(1);
            ArchivesBase selectById = archivesBaseMapper.selectById(typeDoc.getBaseId());
            if (selectById != null) {
                typeDoc.setDataType(selectById.getDataType());
                typeDoc.setColsize(selectById.getColsize());
                //typeDoc.set
                archivesTypeDocMapper.insert(typeDoc);
            }


            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
        }
    }

    @ApiOperation(value = "修改门类字段", notes = "")
    @PutMapping("/archivesType/setCol")
    public Result<String> editTypeCol(@RequestBody ArchivesTypeDoc typeDoc) {
        archivesTypeDocMapper.updateById(typeDoc);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }

    @ApiOperation(value = "删除门类字段", notes = "")
    @DeleteMapping("/archivesType/setCol")
    public Result<String> delTypeCol(@RequestBody List<String> ids) {
        archivesTypeDocMapper.deleteBatchIds(ids);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
    }


    @ApiOperation(value = "列排序", notes = "")
    @PostMapping("/archivesType/sort")
    public Result<String> delCol(@RequestBody @Valid @NotEmpty List<SortCol> sortCols) {
        for (SortCol sortCol : sortCols) {
            ArchivesTypeDoc archivesTypeDoc = new ArchivesTypeDoc();
            archivesTypeDoc.setId(Long.parseLong(sortCol.getId()));
            archivesTypeDoc.setSort(sortCol.getSort());
            archivesTypeDocMapper.updateById(archivesTypeDoc);
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", "");
    }

    @ApiOperation(value = "获取档号生成列", notes = "")
    @GetMapping("/archivesType/genArchivalNumCol/{typeId}/{type}")
    public Result<List<ArchivesTypeDoc>> genArchivalNum(@PathVariable("typeId") String typeId,
                                                        @PathVariable("type") String type) {
        QueryWrapper<ArchivesTypeDoc> queryWrapperCol = new QueryWrapper<ArchivesTypeDoc>();
        queryWrapperCol.eq("extType", type);
        queryWrapperCol.eq("typeId", typeId);
        List<ArchivesTypeDoc> list = archivesTypeDocMapper.selectList(queryWrapperCol);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", list);
    }

    @ApiOperation(value = "设置档号生成规则", notes = "")
    @PostMapping("/archivesType/genArchivalNum")
    public Result<String> genArchivalNum(@RequestBody SetGenArchivalNum setGenArchivalNum) {
        System.out.println(setGenArchivalNum.getGenArchivalNum().toString()+"==========="+setGenArchivalNum.getGenType().toString());
        String newNum = "";
        for (int i = 0; i < setGenArchivalNum.getGenArchivalNum().size(); i++) {
            if (i == 0) {
                newNum = setGenArchivalNum.getGenArchivalNum().get(i);
            } else if (i == setGenArchivalNum.getGenArchivalNum().size() - 1) {
                newNum = newNum + setGenArchivalNum.getGenType().get(i-1)+ setGenArchivalNum.getGenArchivalNum().get(i);
            } else {
                newNum = newNum + setGenArchivalNum.getGenType().get(i-1) + setGenArchivalNum.getGenArchivalNum().get(i);
            }
        }
        System.out.println("newNum:"+newNum);
        ArchivesType entity = new ArchivesType();
        entity.setId(Long.parseLong(setGenArchivalNum.getId()));
        entity.setGenArchivalNum(newNum);
        entity.setGenType(setGenArchivalNum.getGenType().toString().replace("[","").replace("]","").replace(" ",""));
        int rows = archivesTypeMapper.updateById(entity);

        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), "",
                "");
    }



    @ApiOperation(value = "设置分类规则（组卷匹配规则）", notes = "")
    @PostMapping("/archivesType/addRule")
    public Result<String> addRule(@RequestBody SetGenClassNum setGenArchivalNum) {
        String newNum = "";
        for (int i = 0; i < setGenArchivalNum.getGenClassNum().size(); i++) {
            if (i == 0) {
                newNum = setGenArchivalNum.getGenClassNum().get(i);
            } else if (i == setGenArchivalNum.getGenClassNum().size() - 1) {
                newNum = newNum + setGenArchivalNum.getGenClassType() + setGenArchivalNum.getGenClassNum().get(i);
            } else {
                newNum = newNum + setGenArchivalNum.getGenClassType() + setGenArchivalNum.getGenClassNum().get(i);
            }
        }
        ArchivesType entity = new ArchivesType();
        entity.setId(Long.parseLong(setGenArchivalNum.getId()));
        entity.setConstituteRule(newNum);
        entity.setConstituteRuleSymbol(setGenArchivalNum.getGenClassType());
        int rows = archivesTypeMapper.updateById(entity);

        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), "",
                "");
    }

    @ApiOperation(value = "门类排序", notes = "")
    @PostMapping("/archivesType/type/sort")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> sort(@RequestBody List<SortCol> sortCols) {
        try {
            if (sortCols != null && sortCols.size() > 0) {
                for (SortCol sortCol : sortCols) {
                    ArchivesType entity = new ArchivesType();
                    entity.setId(Long.parseLong(sortCol.getId()));
                    entity.setSort(sortCol.getSort());
                    archivesTypeMapper.updateById(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
        }
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
    }


    @ApiOperation(value = "门类字段配置（复制）", notes = "")
    @PostMapping("/archivesType/copyField/{typeId}")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> copyTypeCol(@ApiParam("") @PathVariable("typeId") Long typeId,
                                      @RequestBody List<String> targetIds) {
        QueryWrapper<ArchivesTypeDoc> queryWrapper = new QueryWrapper<ArchivesTypeDoc>();
        queryWrapper.eq("typeId", typeId);
        List<ArchivesTypeDoc> list = archivesTypeDocMapper.selectList(queryWrapper);

        List<ArchivesTypeDoc> batchList = new ArrayList<>();
        for (String targetId : targetIds) {
            QueryWrapper<ArchivesType> qW = new QueryWrapper<ArchivesType>();
            ArchivesType at = archivesTypeMapper.selectById(typeId);
            if (at.getModel().equals("1")) { //卷
                batchList.addAll(buildCopyFieldData(list, "dossier", Long.parseLong(targetId)));
            }

            batchList.addAll(buildCopyFieldData(list, "doc", Long.parseLong(targetId)));
        }

        QueryWrapper<ArchivesTypeDoc> delWrapper = new QueryWrapper<ArchivesTypeDoc>();
        delWrapper.in("typeId", targetIds);
        archivesTypeDocMapper.delete(delWrapper);
        if (archivesTypeDocService.saveBatch(batchList))
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "复制失败", null);


    }


    /**
     * @description:
     * @author: lig
     * @date: 2021/8/19
     */
    @ApiOperation(value = "获取可新增的字段列表", notes = "")
    @GetMapping("/archivesType/newCols/{typeId}/{type}")
    public Result<List<ArchivesTypeDoc>> acquireAddCols(@ApiParam("") @PathVariable("typeId") String typeId,
                                                        @ApiParam("") @PathVariable("type") String type) {
        QueryWrapper<ArchivesTypeDoc> queryWrapperTypeDoc = new QueryWrapper<ArchivesTypeDoc>();
        queryWrapperTypeDoc.eq("typeId", typeId);
        queryWrapperTypeDoc.eq("extType", type);
        List<ArchivesTypeDoc> list = archivesTypeDocMapper.selectList(queryWrapperTypeDoc);
        List<Long> ids = new ArrayList<>();
        for (ArchivesTypeDoc archivesTypeDoc : list) {
            ids.add(archivesTypeDoc.getBaseId());
        }

        List<ArchivesTypeDoc> addCols = new ArrayList<>();
        QueryWrapper<ArchivesBase> queryWrapperBaseList = new QueryWrapper<ArchivesBase>();
        if (ids.size() > 0)
            queryWrapperBaseList.notIn("id", ids);
        List<ArchivesBase> baseList = archivesBaseMapper.selectList(queryWrapperBaseList);

        baseList.forEach((ArchivesBase aBase) -> {
            ArchivesTypeDoc atDoc = new ArchivesTypeDoc();
            atDoc.setTypeId(Long.parseLong(typeId));
            atDoc.setBaseId(atDoc.getId());
            atDoc.setExtColumn(atDoc.getExtColumn());

            ArchivesType at = new ArchivesType();
            at.setModel(DicDocPattern.PATTERN_0.getKey());//件
            if (type.equals((DicDocFileType.DOSSIER.getKey()))) at.setModel(DicDocPattern.PATTERN_1.getKey());
            at.setId(Long.parseLong(typeId));
            addCols.add(ArchivesUtil.initializeArchivesTypeDoc(aBase, at));

        });
//        List<ArchivesBase> baseList = archivesBaseMapper.selectList(queryWrapperBaseList);
        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", addCols);
    }


    /**
     * @description:
     * @author: lig
     * @date: 2021/8/19
     */
    @ApiOperation(value = "批量新增字段列表", notes = "")
    @PostMapping("/archivesType/addField/{typeId}/{type}")
    @OperLog(operModul = "字段管理 - 批量新增", operType = "ADD", operDesc = "字段批量新增功能")
    @Transactional(rollbackFor = Exception.class)
    public Result<List<ArchivesTypeDoc>> addField(@ApiParam("") @PathVariable("typeId") String typeId,
                                                  @ApiParam("") @PathVariable("type") String type, @RequestBody List<ArchivesTypeDoc> fields) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
        if (null == loginInfo)
            return ResultUtil.data(ResultCode.NOT_LOGIN.getCode(), ResultCode.NOT_LOGIN.getMes(), null);

        if (archivesTypeDocService.saveBatch(fields))
            return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
//        if(archivesTypeDocService.saveBatch(fields)) return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", null);
        return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "", null);
    }


    @ApiOperation(value = "设置件号、卷号生成规则", notes = "")
    @PostMapping("/archivesType/genItemOrDossierNum")
    public Result<String> genItemOrDossierNum(@ApiParam("件号长度") @RequestParam(value = "itemNumLength") String itemNumLength,
                                             @ApiParam("卷号长度") @RequestParam(value = "dossierNumLength",required = false) String dossierNumLength,
                                             @ApiParam("") @RequestParam("typeId") String typeId) {

        ArchivesType archivesType2 = archivesTypeMapper.selectById(typeId);
        if(archivesType2==null){
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "门类不存在，修改失败!", "");
        }

        if("0".equals(archivesType2.getAutoDossierItemNum())){
            ArchivesType entity = new ArchivesType();
            entity.setId(Long.parseLong(typeId));
            entity.setGenItemNum(itemNumLength);
            entity.setGenDossierNum(dossierNumLength);
            int rows = archivesTypeMapper.updateById(entity);

            return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), "",
                    "");
        }

        if(Integer.parseInt(itemNumLength)==0){
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "件号长度不能为0，修改失败!", "");
        }
        if(StringUtils.isNotEmpty(dossierNumLength)&&Integer.parseInt(dossierNumLength)==0){
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "卷号长度不能为0，修改失败!", "");
        }

        //修改数据库中，件号，卷号的长度
        //获取最大的件号或卷号
        QueryWrapper<ArchivesDoc> docWrapper=new QueryWrapper<>();
        docWrapper.select("max(convert(itemNum, unsigned)) itemNum , max(convert(dossierNum, unsigned)) dossierNum");
        docWrapper.eq("typeId",typeId);
        docWrapper.eq("isDelete","0");
        ArchivesDoc maxDoc= archivesDocMapper.selectOne(docWrapper);
        String maxItemNum=null;
        String maxDossierNum=null;
        if(maxDoc!=null){
            maxItemNum=maxDoc.getItemNum();
            maxDossierNum=maxDoc.getDossierNum();
        }

        //若修改的长度小于最大件号的长度，则提示修改失败
        if(maxItemNum!=null&&Integer.parseInt(itemNumLength)<maxItemNum.length()){
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "目前最大件号是:"+maxItemNum+"，件号长度小于最大件号长度，修改失败!", "");
        }
        if(StringUtils.isNotEmpty(dossierNumLength)&&maxDossierNum!=null&&Integer.parseInt(dossierNumLength)<maxDossierNum.length()){
            return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "目前最大卷号是:"+maxDossierNum+"，卷号长度小于最大卷号长度，修改失败!", "");
        }
        //获取当前门类的档号设置规则
        ArchivesType archivesType = archivesTypeMapper.selectById(typeId);
        String genArchivalNum = archivesType.getGenArchivalNum();
        String genType = archivesType.getGenType();

        boolean isOnlyItemNum=false;
        boolean isOnlyDossierNum=false;
        boolean isContainNum=false;
        boolean isGenArchivalNum=false;
        if(StringUtils.isNotEmpty(genArchivalNum)&&StringUtils.isNotEmpty(genType)){
            isGenArchivalNum=true;
        }
        //档号规则只有件号
        if("itemNum".equals(genArchivalNum)) isOnlyItemNum=true;
        //档号规则只有卷号
        if("dossierNum".equals(genArchivalNum)) isOnlyDossierNum=true;
        //档号规则包含件号或卷号
        int dossierNumLoc=-1; //卷号位置
        int itemNumLoc=-1; //件号位置
        if(StringUtils.isNotEmpty(genArchivalNum)){
            String [] str=genArchivalNum.split(genType);
            for(int i=0;i<str.length;i++){
                if("dossierNum".equals(str[i])){
                    dossierNumLoc=i;
                    isContainNum=true;
                }
                if("itemNum".equals(str[i])){
                    itemNumLoc=i;
                    isContainNum=true;
                }
            }
        }


        //修改当前门类的件号或卷号长度按照新规定来
        docWrapper=new QueryWrapper<>();
        docWrapper.select("id,dossierId,archivalNum,itemNum,dossierNum,fileType");
        docWrapper.eq("typeId",typeId);
        docWrapper.eq("isDelete","0");
        docWrapper.ne("fileType","scattered");
        List<ArchivesDoc> archivesDocList = archivesDocMapper.selectList(docWrapper);
        for(ArchivesDoc doc :archivesDocList){
            Long dossierId=doc.getDossierId();
            String itemNum=doc.getItemNum();//件号
            String dossierNum =doc.getDossierNum();//卷号
            String archivalNum=doc.getArchivalNum();//档号
            String fileType=doc.getFileType();
            if(StringUtils.isNotEmpty(itemNum) && itemNum.length()< Integer.parseInt(itemNumLength)){//件号长度小于设置长度，添加0
                int forCount=Integer.parseInt(itemNumLength)-itemNum.length();
                for (int i=0;i<forCount;i++){
                    itemNum="0"+itemNum;
                }
                doc.setItemNum(itemNum);
            }else if(StringUtils.isNotEmpty(itemNum) && itemNum.length() > Integer.parseInt(itemNumLength)){//件号长度大于设置长度，缩小0
                itemNum=itemNum.substring(itemNum.length()-Integer.parseInt(itemNumLength));
            }
            if(StringUtils.isNotEmpty(dossierNumLength)&& dossierNum!=null && dossierNum.length()< Integer.parseInt(dossierNumLength)){
                int forCount=Integer.parseInt(dossierNumLength)-dossierNum.length();
                for (int i=0;i<forCount;i++){
                    dossierNum="0"+dossierNum;
                }
                doc.setDossierNum(dossierNum);
            }else if(StringUtils.isNotEmpty(dossierNumLength)&& dossierNum!=null && dossierNum.length() > Integer.parseInt(dossierNumLength)){
                dossierNum=dossierNum.substring(dossierNum.length()-Integer.parseInt(dossierNumLength));
            }

            if(StringUtils.isNotEmpty(archivalNum)&&isGenArchivalNum){
                if(isOnlyItemNum) doc.setArchivalNum(itemNum);
                if(isOnlyDossierNum) doc.setArchivalNum(dossierNum);
                if(isOnlyItemNum==false && isOnlyDossierNum ==false && isContainNum){
                    String [] nums = archivalNum.split(genType);
                    //判断档号是不是以genType结尾的
                    if(archivalNum.endsWith(genType)){
                        if(dossierNumLoc!=-1&&dossierNumLoc!=nums.length) nums[dossierNumLoc]=StringUtils.isEmpty(dossierNum) ? "":dossierNum;
                        if(itemNumLoc!=-1 && itemNumLoc!=nums.length) nums[itemNumLoc]=StringUtils.isEmpty(itemNum) ? "":itemNum;
                    }else{
                        System.out.println("nums："+Arrays.toString(nums));
                        if(dossierNumLoc!=-1 && archivalNum.contains(genType)) nums[dossierNumLoc]=StringUtils.isEmpty(dossierNum) ? "":dossierNum;
                        if(itemNumLoc!=-1 && archivalNum.contains(genType)) {
                            if("doc".equals(fileType)&&dossierId!=0){//卷内文件处理    //若以后卷内档号中的件号，要与卷内文件的件号保持一致，则删除此判断
                                String oldNum = nums[itemNumLoc];
                                if( oldNum.length()< Integer.parseInt(itemNumLength)){//件号长度小于设置长度，添加0
                                    int forCount=Integer.parseInt(itemNumLength)-oldNum.length();
                                    for (int i=0;i<forCount;i++){
                                        oldNum="0"+oldNum;
                                    }
                                }else if( oldNum.length() > Integer.parseInt(itemNumLength)){//件号长度大于设置长度，缩小0
                                    oldNum=oldNum.substring(oldNum.length()-Integer.parseInt(itemNumLength));
                                }
                                nums[itemNumLoc]=oldNum;
                            }else{//件处理
                                nums[itemNumLoc]=StringUtils.isEmpty(itemNum) ? "":itemNum;
                            }

                        }
                    }
                    String archivalNumNew="";
                    for(int i=0;i<nums.length;i++){
                        archivalNumNew=archivalNumNew+nums[i]+genType;
                    }
                    archivalNumNew=archivalNumNew.substring(0,archivalNumNew.lastIndexOf(genType));
                    if(archivalNum.endsWith(genType)){
                        archivalNumNew=archivalNumNew+genType;
                    }
                    doc.setArchivalNum(archivalNumNew);
                }
            }
            doc.setDossierNum(dossierNum);
            doc.setItemNum(itemNum);

            if(StringUtils.isNotEmpty(dossierNum)||StringUtils.isNotEmpty(itemNum)){
                archivesDocMapper.updateById(doc);
            }
        }


        ArchivesType entity = new ArchivesType();
        entity.setId(Long.parseLong(typeId));
        entity.setGenItemNum(itemNumLength);
        entity.setGenDossierNum(dossierNumLength);
        int rows = archivesTypeMapper.updateById(entity);

        return ResultUtil.data(rows > 0 ? ResultCode.RESULT_SUCCESS.getCode() : ResultCode.RESULT_ERROR.getCode(), "",
                "");
    }

    @ApiOperation(value = "获取件号、卷号生成规则", notes = "")
    @GetMapping("/archivesType/genItemOrDossierNum")
    public Result<ArchivesType> genItemOrDossierNumList(@ApiParam("") @RequestParam("typeId") String typeId) {
        QueryWrapper<ArchivesType> queryWrapper = new QueryWrapper<ArchivesType>();
        queryWrapper.eq("id", typeId);
        ArchivesType entity = archivesTypeMapper.selectById(typeId);

        return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", entity);
    }


    private List<ArchivesTypeDoc> buildCopyFieldData(List<ArchivesTypeDoc> list, String extType, Long typeId) {
        List<ArchivesTypeDoc> result = new ArrayList<ArchivesTypeDoc>();

        list.forEach((ArchivesTypeDoc atDoct) -> {
            if (!atDoct.getExtType().equals(extType)) return;
            ArchivesTypeDoc resultAtd = new ArchivesTypeDoc();
            BeanUtils.copyProperties(atDoct, resultAtd);
            resultAtd.setId(null);
            resultAtd.setTypeId(typeId);
            result.add(resultAtd);
        });
        return result;

    }

    /*public static void main(String[] args) {

        String str="1-2-3";
        String [] st = str.split("-");
        for (int i=0;i<st.length;i++){
            System.out.println(st[i]);
        }

    }*/
}
